package com.it.od.lee.leetcode;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: liminghui
 * @date: 2024/3/30 14:04
 * @version: 1.0
 * @description: 128. 最长连续序列
 * 给定一个未排序的整数数组 nums ，找出数字连续的最长序列（不要求序列元素在原数组中连续）的长度。
 * 请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
 * 示例 1：
 * 输入：nums = [100,4,200,1,3,2]
 * 输出：4
 * 解释：最长数字连续序列是 [1, 2, 3, 4]。它的长度为 4。
 * 示例 2：
 * 输入：nums = [0,3,7,2,5,8,4,6,0,1]
 * 输出：9
 */
public class Lee128 {
    public static void main(String[] args) {
        int[] nums = {0,3,7,2,5,8,4,6,0,1};
        int res = longestConsecutive2(nums);
        System.out.println(res);
    }

    public static int longestConsecutive(int[] nums) {
        Arrays.sort(nums);
        int max = 0;
        int right = 0;
        int len = 0;
        int n = nums.length;
        while (right < n) {
            if (right > 0) {
                if (nums[right] == nums[right - 1]) {
                    right++;
                    continue;
                } else if (nums[right] - nums[right - 1] != 1) {
                    len = 0;
                }
            }
            right++;
            len++;
            max = Math.max(max, len);
        }
        return max;
    }

    // 并查集 35ms
    public static int longestConsecutive2(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        UnionFindSet ufs = new UnionFindSet(n);
        for (int i = 1; i < n; i++) {
            int l = i - 1;
            while (i < n && nums[i] == nums[l]) { // 判断数字相同就跳过。
                i++;
            }
            if (i < n && nums[i] - nums[l] == 1) {
                ufs.union(l, i);
            }
        }
        int[] father = ufs.father;
        Map<Integer, Integer> map = new HashMap<>();
        for (int j : father) {
            map.put(j, map.getOrDefault(j, 0) + 1);
        }
        int max = Arrays.stream(map.values().stream().mapToInt(x -> x).toArray()).max().orElse(0);
        return max;

    }

    public static class UnionFindSet {
        private int[] father;

        public UnionFindSet(int n) {
            this.father = new int[n];
            for (int i = 0; i < n; i++) {
                father[i] = i;
            }
        }

        public int find(int x) {
            if (father[x] != x) {
                father[x] = find(father[x]);
            }
            return father[x];
        }

        public void union(int x, int y) {
            int x_fa = find(x);
            int y_fa = find(y);
            if (x_fa != y_fa) {
                father[y_fa] = x_fa;
            }
        }
    }
}
